//
//  WNComposeView.swift
//  XLWeibo
//
//  Created by 风不会停息 on 2017/7/30.
//  Copyright © 2017年 风不会停息. All rights reserved.
//

import UIKit
import pop

class WNComposeView: UIView {

    private lazy var composeButtonArray : [WNComposeButton] = [WNComposeButton]()
    
    // MARK:--- 懒加载控件
    
    fileprivate lazy var bgImageView : UIImageView = {
        
        let image = self.getScreenShot().applyLightEffect()
        
        let imageView = UIImageView(image: image)
        
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        addSubview(bgImageView)
        
        addChildButton()
        
        startPopSringAnimation(isUp: true)
    }
    
    private func addChildButton(){
        
        let buttonWidth : CGFloat = 80
        
        let buttonHeight : CGFloat = 110
        
        let buttonMargin : CGFloat = (width - 3 * buttonWidth) / 4
        
        for i in 0..<6{
            //列索引
            let colIndex = i % 3
            //行索引
            let rowIndex = i / 3
            
            let button = WNComposeButton()
            
            button.addTarget(self, action: #selector(composeButtonAction(btn:)), for: .touchUpInside)
            
            //  设置x坐标
            button.x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonMargin
            //  设置y坐标
            button.y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * buttonMargin + ScreenHeight
            //  设置大小
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            button.setImage(UIImage(named: "tabbar_compose_idea"), for: .normal)
            button.setTitle("\(i)", for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.setTitleColor(UIColor.gray, for: .normal)
            addSubview(button)
            //  添加到撰写数组
            composeButtonArray.append(button)
        }
    }
    
    @objc private func composeButtonAction(btn : WNComposeButton){
        
        UIView.animate(withDuration: 0.25, animations: {
            
            for button in self.composeButtonArray {
                //  设置按钮的透明度
                button.alpha = 0.3
                if button == btn {
                    //  放大
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                } else {
                    //  缩小
                    button.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
                }
            }

            
        }) { (_) in
            
            UIView.animate(withDuration: 0.25, animations: {
                for button in self.composeButtonArray {
                    //  设置按钮的透明度
                    button.alpha = 1
                    button.transform = CGAffineTransform.identity
                }
            }, completion: { (_) in
                print("弹出发微博界面")
            })

        }
    }
    
    //执行弹簧动画
    private func startPopSringAnimation(isUp : Bool){
        
        if isUp == false {
            
            composeButtonArray = composeButtonArray.reversed()
        }
        
        for (i, composeButton) in composeButtonArray.enumerated() {
            //  创建弹簧动画对象，kPOPViewCenter
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            if isUp {
                //  动画目的地
                animation?.toValue = CGPoint(x: composeButton.centerX, y: composeButton.centerY - 350)
            } else {
                //  动画目的地
                animation?.toValue = CGPoint(x: composeButton.centerX, y: composeButton.centerY + 350)
            }
            
            //  设置弹簧系数[0-20] 弹力 越大则震动幅度越大
            animation?.springBounciness = 10
            //  springSpeed 默认值: 12.0  [0-20] 速度 越大则动画结束越快
            animation?.springSpeed = 10
            //  设置动画时间间隔 CACurrentMediaTime: 现在距离开机的时间差
            animation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            //  执行弹簧动画
            composeButton.pop_add(animation, forKey: nil)
        }

    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //  向下的pop动画
        startPopSringAnimation(isUp: false)
        //  主线程移除视图
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
            self.removeFromSuperview()
        }
    }

    
    //截屏方法
    private func getScreenShot()->UIImage{
        
        //获取window
        let window = UIApplication.shared.keyWindow!
        
        //开启图片上下文
        UIGraphicsBeginImageContext(window.size)
        
        //截屏区域
        let rect = CGRect(origin: CGPoint.zero, size: window.size)
        
        //截屏 指定区域 是否刷新屏幕后截屏
        window.drawHierarchy(in: rect, afterScreenUpdates: false)
        
        //图形上下文中获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //结束图形上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    
}
